package com.zhu.shiro.cacheManager.memory;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by DELL on 2015/12/30.
 */
public class CustomeCache<K, V> implements Cache<K, V> {
    private String prefix;
    private int prefixLength;
    private Map<String, V> cacheMap = new ConcurrentHashMap<String, V>();

    public CustomeCache(String prefix){
        this.prefix = prefix;
        if(prefix != null){
            prefixLength = prefix.length();
        }
    }

    @Override
    public V get(K k) throws CacheException {
        return cacheMap.get(generatKey(k));
    }

    @Override
    public V put(K k, V v) throws CacheException {
        return cacheMap.put(generatKey(k), v);
    }

    @Override
    public V remove(K k) throws CacheException {
        return cacheMap.remove(generatKey(k));
    }

    @Override
    public void clear() throws CacheException {
        cacheMap.clear();
    }

    @Override
    public int size() {
        return cacheMap.size();
    }

    @Override
    public Set<K> keys() {
        Set<K> keySet = new HashSet<K>();

         for(String key : cacheMap.keySet()){
             if(key != null) {
                 keySet.add((K) key.substring(prefixLength));
             }
         }

        return keySet;
    }

    @Override
    public Collection<V> values() {
        return cacheMap.values();
    }

    protected String generatKey(K k){
        return prefix + k;
    }
}
